import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';

import '../../../models/information.dart';
import '../../../services/auth_service.dart';
import '../../../services/information_service.dart';

class AddInformationLogic extends GetxController {
  final AuthService _authService = AuthService();
  final InformationService _informationService = InformationService();

  final titleController = TextEditingController();
  final contentController = TextEditingController();

  final isLoading = false.obs;
  final ImagePicker _imagePicker = ImagePicker();
  final Rx<File?> selectedImage = Rx<File?>(null);

  @override
  void onClose() {
    titleController.dispose();
    contentController.dispose();
    super.onClose();
  }

  Future<void> pickImage(ImageSource source) async {
    try {
      final XFile? pickedFile = await _imagePicker.pickImage(
        source: source,
        imageQuality: 80, // 压缩图片质量以减小文件大小
      );

      if (pickedFile != null) {
        selectedImage.value = File(pickedFile.path);
      }
    } catch (e) {
      SmartDialog.showToast('选择图片失败: $e');
    }
  }

  void showImagePickerOptions() {
    Get.bottomSheet(
      Container(
        color: Colors.white,
        child: Wrap(
          children: [
            ListTile(
              leading: Icon(Icons.photo_camera),
              title: Text('拍照'),
              onTap: () {
                Get.back();
                pickImage(ImageSource.camera);
              },
            ),
            ListTile(
              leading: Icon(Icons.photo_library),
              title: Text('从相册选择'),
              onTap: () {
                Get.back();
                pickImage(ImageSource.gallery);
              },
            ),
            if (selectedImage.value != null)
              ListTile(
                leading: Icon(Icons.delete, color: Colors.red),
                title: Text('删除当前图片', style: TextStyle(color: Colors.red)),
                onTap: () {
                  Get.back();
                  selectedImage.value = null;
                },
              ),
          ],
        ),
      ),
    );
  }

  // 保存图片到应用文件夹
  Future<String?> _saveImageToAppDirectory(File imageFile) async {
    try {
      final appDir = await getApplicationDocumentsDirectory();
      final fileName = 'image_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final savedImage = await imageFile.copy('${appDir.path}/$fileName');
      return savedImage.path;
    } catch (e) {
      SmartDialog.showToast('保存图片失败: $e');
      return null;
    }
  }

  Future<void> saveInformation() async {
    if (titleController.text.isEmpty || contentController.text.isEmpty) {
      SmartDialog.showToast('标题和内容不能为空');
      return;
    }

    isLoading.value = true;

    try {
      final userId = await _authService.getCurrentUserId();
      if (userId == null) {
        SmartDialog.showToast('用户未登录');
        return;
      }

      // 如果有选择图片，则保存到应用文件夹
      String? imagePath;
      if (selectedImage.value != null) {
        imagePath = await _saveImageToAppDirectory(selectedImage.value!);
      }

      final now = DateTime.now();
      final information = Information(
        title: titleController.text.trim(),
        content: contentController.text.trim(),
        imageUrl: imagePath,
        publishDate: now.toString(),
        publisherId: userId,
      );

      await _informationService.insertInformation(information);
      SmartDialog.showToast('信息发布成功');
      Get.back();
    } catch (e) {
      SmartDialog.showToast('发布失败: $e');
    } finally {
      isLoading.value = false;
    }
  }
}
